package Servlet.Blog.util;


import Servlet.Blog.entity.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liyy
 * @description
 * @time 2020/10/12 11:27
 */
public class DBUtil {
    private static String Driver = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/myblog?useUnicode=true&characterEncoding=utf8";
    private static String username = "root";
    private static String password = "root";
    private static Connection conn = null;

    //连接数据库
    public static Connection getConnection() {
        if(conn == null) {
            try {
                Class.forName(Driver);//加载驱动器
                conn = (Connection) DriverManager.getConnection(url,
                        username,
                        password);
                System.out.println("开始数据库连接");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return conn;
    }

    //关闭数据库联接
    public static void CloseConn() {
        if(conn != null) {
            try {
                conn.close();
                System.out.println("关闭数据库连接");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        getConnection();
        List<User> userList = new ArrayList<>();
        String sql = "select * from blogusers";
        try{
            PreparedStatement pstmt = conn.prepareStatement(sql);
            ResultSet rst = pstmt.executeQuery();
            while(rst.next()){
                User user = new User();
                user.setId(rst.getInt("id"));
                user.setUsername(rst.getString("username"));
                user.setUserpass(rst.getString("userpass"));
                user.setCreationtime(rst.getLong("creationtime")+"");
                user.setStatus(rst.getByte("status"));
                userList.add(user);
            }
        }catch (Exception e){
            //logger.error("queryUserList error",e);
            System.out.println(e.getMessage());
        }

        CloseConn();
    }
}
